package cn.nubia.admin.sysconfig.controller;

import cn.nubia.admin.common.mybatis.bean.Paged;
import cn.nubia.admin.common.springmvc.Response;
import cn.nubia.admin.sysconfig.bean.Menu;
import cn.nubia.admin.sysconfig.query.MenuQuery;
import cn.nubia.admin.sysconfig.service.MenuService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * Created by justin on 15/7/29.
 */
@Controller
@RequestMapping(value = "/admin/menu/")
public class MenuController {


    @Autowired
    MenuService menuService;

    @RequiresPermissions("sys:syscfg:menu:list")
    @RequestMapping(value = "list")
    public ModelAndView list(MenuQuery query){
        ModelAndView modelAndView = new ModelAndView("/system/menulist");
        List<Menu> menus = menuService.listMenus(query);
        modelAndView.addObject("menus",menus);
        return modelAndView;
    }

    @RequestMapping(value = "edit")
    public ModelAndView edit(Integer id,Integer parentId){
        ModelAndView modelAndView = new ModelAndView("/system/editMenu");
        Menu menu = null;
        if(id != null){
            menu = menuService.get(id);
            Menu parentInfoMenu = menuService.getParentInfo(menu.getParentId());
            menu.setParentName(parentInfoMenu.getParentName());
        }else if (parentId!=null){
            menu = menuService.getParentInfo(parentId);
        }else{
            menu = new Menu();
        }
        modelAndView.addObject("menu",menu);
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping(value = "save")
    public Response<Boolean> save(Menu menu, BindingResult result){
        if (result.hasErrors()) return Response.getFailedResponse(result.getAllErrors().get(0).getDefaultMessage());
        boolean sucess = menuService.saveMenu(menu);
        return Response.getSuccessResponse(sucess);
    }

    @ResponseBody
    @RequestMapping(value = "delete")
    public Response<Boolean> delete(Integer id){
        menuService.delete(id);
        return Response.getSuccessResponse(true);
    }
}
